package com.atguigu.gmall.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.gateway.properties.AuthUrlProperties;
import com.atguigu.gmall.user.entity.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description
 * @Return
 * @Author https://weiranyi.github.io
 * @Date Created in 2022-12-15 15:49
 **/
@Component
@Slf4j
public class UserAuthGlobalFilter implements GlobalFilter {
    @Autowired
    AuthUrlProperties urlProperties;
    @Autowired
    StringRedisTemplate redisTemplate;
    AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("请求开始--------------------------------------------");
        // 1.得到path
        String path = exchange.getRequest().getURI().getPath();
        // 2.1 如果是静态资源，直接放行
        List<String> anyoneUrl = urlProperties.getAnyoneUrl();
        long count = urlProperties.getAnyoneUrl().stream()
                .filter(pattern -> pathMatcher.match(pattern, path)).count();
        if (count > 0) {
            log.info("静态资源直接放行");
            return chain.filter(exchange);
        }
        // 2.2 想内部路径，直接拒绝
        long denyCount = urlProperties.getDenyUrl().stream()
                .filter(pattern -> pathMatcher.match(pattern, path)).count();
        if (denyCount > 0) {
            log.info("非法访问");
            Result<String> result = Result.build("", ResultCodeEnum.PERMISSION);
            return responseJson(exchange, result);
        }
        // 2.3 有限权限访问的
        long loginCount = urlProperties.getAuthUrl().stream()
                .filter(pattern -> pathMatcher.match(pattern, path)).count();
        if (loginCount > 0) {
            // 能拿到令牌说明登录了，BUT为了防止未登录的情况伪造
            // 1、获取请求头或者cookie中携带的用户令牌标识
            String token = getToken(exchange);
            // 2.从请求的token中获取redis上已登录的用户信息
            UserInfo userInfo = getUserInfo(token);
            if (StringUtils.isEmpty(token) || userInfo == null) {
                return redirectToLoginPage(exchange, urlProperties.getLoginPage());
            }
        }

        // filter放行,立即得到mono，该方法是非阻塞的
        Mono<Void> filter = chain.filter(exchange).doFinally((item) -> {
            log.info("请求结束--------------------------------------------");
        });

        UserInfo userInfo = getUserInfo(getToken(exchange));
        return userIdThrough(exchange, chain, userInfo);
    }

    private Mono<Void> userIdThrough(ServerWebExchange exchange, GatewayFilterChain chain, UserInfo userInfo) {
        // 1.透传
        ServerHttpRequest.Builder reqBuilder = exchange.getRequest().mutate();
        // 2.用户id放请求头
        if (userInfo != null) {
            log.info("用户信息放在头中向下透传");
            reqBuilder.header(RedisConst.USER_ID_HEADER, userInfo.getId().toString()).build();
        }
        // 3.临时id
        String tempId = getTempId(exchange);
        if (!StringUtils.isEmpty(tempId)) {
            log.info("用户临时id信息放在头中向下透传");
            reqBuilder.header(RedisConst.USER_TEMP_ID_HEADER, tempId).build();
        }
        return chain.filter(exchange);
    }

    private String getTempId(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("userTempId");
        if (!StringUtils.isEmpty(token)) {
            return token;
        }
        HttpCookie first = request.getCookies().getFirst("userTempId");
        //未登录时，没有cookie
        if (first != null) {
            return first.getValue();
        }
        return null;
    }

    private Mono<Void> redirectToLoginPage(ServerWebExchange exchange, String loginPage) {
        //请求来源路径
        String uri = exchange.getRequest().getURI().toString();
        //设置要重定向的地址
        loginPage += "?originUrl=" + uri.toString();
        ServerHttpResponse response = exchange.getResponse();
        //1、[重定向第一步]设置响应状态码  302
        response.setStatusCode(HttpStatus.FOUND);
        //2、[重定向第二步]设置响应头  Location: http://passport.gmall.com/login.html
        response.getHeaders().set("Location", loginPage);
        return response.setComplete();
    }

    private Mono<Void> responseJson(ServerWebExchange exchange, Result result) {
        // 得到响应对象
        ServerHttpResponse response = exchange.getResponse();
        String json = JSON.toJSONString(result);
        // 得到数据的DataBuffer
        DataBuffer dataBuffer = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        return response.writeWith(Mono.just(dataBuffer));
    }

    private UserInfo getUserInfo(String token) {
        String json = redisTemplate.opsForValue().get(RedisConst.LOGIN_USER + token);
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return JSON.parseObject(json, UserInfo.class);
    }

    private String getToken(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("token");
        if (!StringUtils.isEmpty(token)) {
            return token;
        }
        HttpCookie first = request.getCookies().getFirst("token");
        //未登录时，没有cookie
        if (first != null) {
            return first.getValue();
        }
        return null;
    }
}
